package console

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"http_proxy_v2/internal/httproxy"
	"http_proxy_v2/pkg/logger"
	"io"
	"os"

	//"http_proxy_v2/pkg/logger"
	"net/http"
	"time"
)

var (
	err error
)

// 管理后台

func RunServer() {
	logger.Init()

	f, err := os.OpenFile("logs/access.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		logrus.Info(err)
	}
	gin.DefaultWriter = io.MultiWriter(f, os.Stdout)

	r := gin.Default()

	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})
	r.GET("/", func(c *gin.Context) {
		logrus.Info("asdasdadasd")
		c.JSON(200, gin.H{
			"message": "hello world",
		})
	})

	r.GET("/disable", func(c *gin.Context) {
		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Microsecond)
		defer cancel()
		err := httproxy.Shutdown(8081, ctx)
		c.JSON(200, gin.H{
			"err": err,
		})
	})

	//err := r.Run() // listen and serve on 0.0.0.0:8080
	server := &http.Server{
		Addr:           ":8848",
		Handler:        r,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	err = server.ListenAndServe()
	if err != nil {
		//logger.Error("启动服务失败")
	}
	return
}
